# -*- coding:utf-8 -*-

import sqlite3
from Queue import Queue
from threading import Thread
class Nest(Thread):
    def __init__(self, name, database):
        Thread.__init__(self, name = name)
        self.database = database
        self.queue = Queue()       
    def put(self, items):
        self.queue.put(items)
    
    def run(self):
        while True:
            item = self.queue.get()
            try:
                self.insert(item[0], item[1])
            except Exception, e:
                print e
            
    def connect(self):
        cx = sqlite3.connect(self.database)
        return cx
    
    def initFromSql(self,filename = ''):
        fp = open(filename, 'r')
        cx = self.connect()
        cu = cx.cursor()
        for line in fp.readlines():
            cu.execute(line)
            cx.commit()
        cx.close()
    
    def insert(self, tablename, data):
        cx = self.connect()
        cu = cx.cursor()
        try:
            keys = []
            valus = []
            for k, v in data.items():
                keys.append(k)
                valus.append(v)
            keys = ','.join(keys)
            sql = 'insert into ' + tablename + '(' + keys + ')' + 'values(' + ','.join(['?']*len(valus))+')'
            cu.execute(sql, valus)
            cx.commit()
        except Exception,e:
            print e
            return False
        return True
    
if __name__ == "__main__":
    #initDB()
    pass        
                         